package com.jack.helloworld.activity;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.jack.helloworld.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SimpleSpinnerActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    TextView tvSimpleSpinner;
    Spinner simpleSpinner;

    SimpleAdapter simpleAdapter;
    List<Map<String, Object>> listData;

    String[] types = new String[]{"img", "text"};
    int[] keys = new int[]{R.id.ivSpinner, R.id.tvSpinner};
    List<String> data = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_spinner);

        initView();
        initData();
    }
    private void initView() {
        tvSimpleSpinner = (TextView) findViewById(R.id.tvSimpleSpinner);
        simpleSpinner = (Spinner) findViewById(R.id.simpleSpinner);

    }


    private void initData() {
        data.add("beijing");
        data.add("shanghai");
        data.add("shenzheng");
        data.add("guangzhou");

        tvSimpleSpinner.setText("select beijing");

        listData = new ArrayList<Map<String, Object>>();
        simpleAdapter = new SimpleAdapter(this, getData(), R.layout.spinner_view_item, types, keys);
        simpleAdapter.setDropDownViewResource(R.layout.spinner_view_item);
        simpleSpinner.setAdapter(simpleAdapter);

        simpleSpinner.setOnItemSelectedListener(this);
    }


    private List<Map<String, Object>> getData() {

        for (int i = 0; i < data.size(); i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("img", R.mipmap.ic_launcher);
            map.put("text", data.get(i));
            listData.add(map);
        }

        return listData;
    }


    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
        String text = simpleSpinner.getItemAtPosition(position).toString();
        tvSimpleSpinner.setText("select " + text);
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }
}
